<?php

namespace Wap\Controller;

use Common\Service\Sms\ShortMessageService;
use Think\Controller;
use Think\Model;
use Think\Verify;
use User\Model\FactoryModel;
use User\Model\MemberClassModel;
use User\Model\MemberModel;
use User\Model\MemberPropertyModel;
use Wap\Service\WeixinService;

//header('Access-Control-Allow-Origin: *');
class MemberController extends Controller
{

    public $_member_class;//活动信息
    public $wxuser;//活动绑定的微信号
    public $user;//微信用户

    public function __construct()
    {
        parent::__construct();

        if (!headers_sent() && // 如果页面头部信息还没有输出--
            extension_loaded("zlib") && // 而且php已经加载了zlib扩展--
            strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")
        ) //而且浏览器接受GZIP--
        {
            ini_set('zlib.output_compression', 'On');
            ini_set('zlib.output_compression_level', '4');
        }

        $this->handleCriteriaMember();
        $this->handleCriteriaWxuser();
    }

    /**
     *函数名: index
     *函数描述: 获取微信网页静默授权CODE、加载所有作品主页模板
     * @param string $_GET ['code'];
     * @return object 模板
     */
    public function index()
    {
        return $this->display("apply");
    }

    public function indexNext()
    {
        $params = I("get.", "", "");
        if (empty($params['phone'])) {
            $this->ajaxReturn(array("status" => -1, "result" => "请填写手机号码"));
        }
        $cond['phone'] = $params['phone'];
        $cond['status'] = array("NEQ", MemberModel::STATUS_DELETE);
        $cond['token'] = $this->wxuser['token'];
        $member = M("member")->where($cond)->find();
        if (!empty($member)) {
            $this->ajaxReturn(array("status" => -2, "result" => "此手机号码已注册请直接登录"));
        }
        if (empty($params['code'])) {
            $this->ajaxReturn(array("status" => -3, "result" => "验证码不正确"));
        }
        $verify = new Verify();
        if (!$verify->check($params['code'], '')) {
            $this->ajaxReturn(array("status" => -3, "result" => "验证码不正确!"));
        }
        if (empty($params['sms'])) {
            $this->ajaxReturn(array("status" => -4, "result" => "短信验证码不正确"));
        }
        $sms = session("member_sms");
        if ($sms != strtoupper($params['sms'])) {
            $this->ajaxReturn(array("status" => -4, "result" => "短信验证码不正确!" . $sms . "|" . strtoupper($params['sms'])));
        }
        $this->ajaxReturn(array('status' => 1, "result" => "验证成功"));
    }

    /*
    *是否合法活动
    */
    private function handleCriteriaMember()
    {
        $cond['class_id'] = IS_GET ? I("get.id", -1, "") : I("post.id", -1, "");
        if (empty($cond['class_id']) || $cond['class_id'] == -1) {
            $cond['class_id'] = I("get.state");
        }
        $cond['status'] = MemberClassModel::STATUS_ACTIVE;
        $this->_member_class = M("member_class")->where($cond)->find();
        if (empty($this->_member_class)) {
            $this->error("会员信息已过期", "#");
        }
    }

    /*
    *微信公众号信息
    */
    private function handleCriteriaWxuser()
    {
        $this->wxuser = WeixinService::getWxuser($this->_member_class['token']);
    }

    public function getClass()
    {
        $cond['status'] = MemberClassModel::STATUS_ACTIVE;
        $cond['token'] = $this->wxuser['token'];
        $class_id = I("get.class_id", "", "");
        if (!empty($class_id)) {
            $cond['class_id'] = $class_id;
        }
        $member_class = M("member_class")->where($cond)->select();
        $this->ajaxReturn(array("status" => 1, "result" => "成功", "member_class" => $member_class));
    }

    public function getVerify()
    {
        $verify = new Verify();
        $verify->entry();
    }

    public function getSms()
    {
        $phone = I("get.phone", "", "");
        if (empty($phone)) {
            $this->ajaxReturn(array('status' => -1, 'result' => "请填写电话号码"));
        }
        $authcode = '';
        for ($i = 0; $i < 4; $i++) {
            $randAsciiNumArray = array(rand(48, 57), rand(65, 90));
            $randAsciiNum = $randAsciiNumArray [rand(0, 1)];
            $randStr = chr($randAsciiNum);
            $authcode .= $randStr;
        }
        $msg = "您的验证码为：" . $authcode;
        session("member_sms", $authcode);
        $result = FactoryModel::sendMsg($phone, $msg);
        $this->ajaxReturn(array('status' => 1, 'result' => $result));
    }

    public function login()
    {
        $login_phone = session("login_phone");
        if (!empty($login_phone)) {
            return $this->display("info");
        }
        return $this->display();
    }

    public function loginNext()
    {
        $params = I("get.", "", "");
        if (empty($params['phone'])) {
            $this->ajaxReturn(array("status" => -1, "result" => "请填写手机号码"));
        }
        $cond['phone'] = $params['phone'];
        $cond['status'] = array("NEQ", MemberModel::STATUS_DELETE);
        $cond['token'] = $this->wxuser['token'];
        $member = M("member")->where($cond)->find();
        if (empty($member)) {
            $this->ajaxReturn(array("status" => -1, "result" => "登录失败，请检查手机号码/短信验证码"));
        }
        if (empty($params['sms'])) {
            $this->ajaxReturn(array("status" => -3, "result" => "短信验证码不正确"));
        }
        $sms = session("member_sms");
        if ($sms != strtoupper($params['sms'])) {
            $this->ajaxReturn(array("status" => -3, "result" => "短信验证码不正确!" . $sms . "|" . $params['sms']));
        }
        session("login_phone", $params['phone']);
        $cond_edit['member_id'] = $member['member_id'];
        $data['last_login_date'] = date("Y-m-d H:i:s");
        M("member")->where($cond_edit)->save($data);
        $this->ajaxReturn(array('status' => 1, "result" => "登录成功"));
    }

    public function detail()
    {
        $this->display("info");
    }

    public function getDetail()
    {
        $params = I("get.", "", "");
        $phone = session("login_phone");
        if (empty($phone)) {
            $this->ajaxReturn(array("status" => -99, "result" => "登录过期"));
        }
        $cond['phone'] = $phone;
        $cond['status'] = array("NEQ", MemberModel::STATUS_DELETE);
        $cond['token'] = $this->wxuser['token'];
        if (isset($params['class_id'])) {
            $cond['class_id'] = $params['class_id'];
        }
        $field = "member_id,class_id,name,province,city,district,address,phone,status,result";
        $member = M("member")->where($cond)->getField($field);
        if (empty($member)) {
            $this->ajaxReturn(array("status" => -1, "result" => "会员信息错误"));
        }
        $class_ids = array();
        $regionids = array();
        foreach ($member as $member_each) {
            $class_ids[] = $member_each['class_id'];
            $regionids[] = $member_each['province'];
            $regionids[] = $member_each['city'];
            $regionids[] = $member_each['district'];
        }

        $regionids = array_unique($regionids);
        $regionids = array_values($regionids);
        $cond_region['id'] = array("IN", $regionids);
        $region = M("region")->where($cond_region)->getField("id,regionname");
        foreach ($member as &$member_each) {
            if (isset($region[$member_each['province']])) {
                $member_each['province_name'] = $region[$member_each['province']];
            } else {
                $member_each['province_name'] = "";
            }
            if (isset($region[$member_each['city']])) {
                $member_each['city_name'] = $region[$member_each['city']];
            } else {
                $member_each['city_name'] = "";
            }
            if (isset($region[$member_each['district']])) {
                $member_each['district_name'] = $region[$member_each['district']];
            } else {
                $member_each['district_name'] = "";
            }
        }

        $class_ids = array_unique($class_ids);
        $class_ids = array_values($class_ids);
        $cond_class['class_id'] = array("IN", $class_ids);
        $member_class = M("member_class")->where($cond_class)->select();
        if (empty($member_class)) {
            $this->ajaxReturn(array("status" => -2, "result" => "会员类别信息错误"));
        }
        $property_ids = "";
        foreach ($member_class as $member_class_each) {
            $property_ids .= $member_class_each['property_ids'];
        }
        $property_ids_arr = explode(",", $property_ids);
        $property_ids_arr = array_unique($property_ids_arr);
        $property_ids_arr = array_values($property_ids_arr);
        $ext = array();
        if (!empty($property_ids_arr)) {
            $cond_property['property_id'] = array("IN", $property_ids_arr);
            $cond_property['status'] = MemberPropertyModel::STATUS_ACTIVE;
            $ext = M("member_property")->where($cond_property)->select();
        }
        $this->ajaxReturn(array("status" => 1, "result" => "成功",
            'member' => $member, 'ext' => $ext, 'member_class' => $member_class));
    }

    public function add()
    {
        $params = I("post.", "", "");
        if (empty($params['phone'])) {
            $this->ajaxReturn(array("status" => -1, "result" => "请填写电话号码"));
        }
        $class = $params['class'];
        if (empty($class)) {
            $this->ajaxReturn(array("status" => -4, "result" => "请选择会员类型"));
        }
        if (empty($params['name'])) {
            $this->ajaxReturn(array("status" => -5, "result" => "请填写姓名"));
        }
        $data = array();
        foreach ($class as $key => $add_class) {
            $data[] = $this->add_class($key);
        }
        M("member")->addall($data);
        $this->ajaxReturn(array("status" => 1, "result" => "成功"));
    }

    private function add_class($key)
    {
        $params = I("post.", "", "");

        $class = $params['class'][$key];

        $cond_member['class_id'] = $cond_class['class_id'] = $data['class_id'] = $key;
        $cond_class['status'] = MemberClassModel::STATUS_ACTIVE;
        $cond_class['token'] = $this->wxuser['token'];
        $member_class = M("member_class")->where($cond_class)->find();
        if (empty($member_class)) {
            $this->ajaxReturn(array("status" => -4, "result" => "请选择有效会员类型!"));
        }
        $cond_member['phone'] = $params['phone'];
        $cond_member['status'] = array("NEQ", MemberModel::STATUS_DELETE);
        $cond_member['token'] = $this->wxuser['token'];
        $member = M("member")->where($cond_member)->find();
        if (!empty($member)) {
            $this->ajaxReturn(array("status" => -3, "result" => "号码已经被注册"));
        }
        $data['name'] = $params['name'];
        $data['province'] = empty($params['province']) ? 0 : $params['province'];
        $data['city'] = empty($params['city']) ? 0 : $params['city'];
        $data['district'] = empty($params['district']) ? 0 : $params['district'];
        $data['address'] = empty($params['address']) ? "" : $params['address'];
        $data['phone'] = $params['phone'];
        $data['channel'] = MemberModel::CHANNEL_WX;
        $data['token'] = $this->wxuser['token'];
        if ($member_class['need_check'] == 1) {
            $data['status'] = MemberModel::STATUS_PENDING;
        } else {
            $data['status'] = MemberModel::STATUS_ACTIVE;
        }


        $property_ids = $member_class['property_ids'];
        $property_ids_arr = explode(",", $property_ids);
        if (!empty($property_ids_arr)) {
            $cond_property['property_id'] = array("IN", $property_ids_arr);
            $cond_property['status'] = MemberPropertyModel::STATUS_ACTIVE;
            $ext = M("member_property")->where($cond_property)->select();
            foreach ($ext as $val) {
                $check = false;
                foreach ($class as $property_value) {
                    if (array_key_exists($val['property_id'], $property_value)) {
                        if (!empty($property_value[$val['property_id']])) {
                            $check = true;
                        }
                        if ($val['format'] == 1) {
                            $img_upload = FactoryModel::ajaxImgUpload($property_value[$val['property_id']], "member");
                            if ($img_upload['code'] == '1') {
                                $data['ext'] .= $val['property_id'] . "|" . $img_upload['msg'] . ",";
                            } else {
                                $this->ajaxReturn(array("status" => -11, "result" => $img_upload['msg'] . $val['name']));
                            }
                        } else {
                            $data['ext'] .= $val['property_id'] . "|" . $property_value[$val['property_id']] . ",";
                        }
                    }
                }
                if ($val['style'] == 1 && $check == false) {
                    $this->ajaxReturn(array("status" => -10, "result" => "请填写" . $val['name']));
                }
            }
        }
        return $data;
    }

    public function getProvince()
    {
        $cond_province['regiontype'] = 1;
        $province = M("region")->where($cond_province)->select();
        $this->ajaxReturn(array("status" => 1, "result" => "成功", "province" => $province));
    }

    public function getCity()
    {
        $cond_city['regiontype'] = 2;
        $citys = M("region")->where($cond_city)->getField("id,parentid,regionname");
        $city = array();
        foreach ($citys as $each_city) {
            if (isset($city[$each_city['parentid']])) {
                $city[$each_city['parentid']][] = $each_city;
            } else {
                $city[$each_city['parentid']] = array($each_city);
            }
        }
        $this->ajaxReturn(array("status" => 1, "result" => "成功", "city" => $city));
    }

    public function getDistrict()
    {
        $cond_district['regiontype'] = 3;
        $districts = M("region")->where($cond_district)->getField("id,parentid,regionname");
        $district = array();
        foreach ($districts as $each_district) {
            if (isset($district[$each_district['parentid']])) {
                $district[$each_district['parentid']][] = $each_district;
            } else {
                $district[$each_district['parentid']] = array($each_district);
            }
        }
        $this->ajaxReturn(array("status" => 1, "result" => "成功", "district" => $district));
    }

    public function getExt()
    {
        $params = I("get.", "", "");
        if (empty($params['class_id'])) {
            $this->ajaxReturn(array("status" => -1, "result" => "请选择会员类型"));
        }
        $cond_class['class_id'] = $params['class_id'];
        $member_class = M("member_class")->where($cond_class)->find();
        if (empty($member_class)) {
            $this->ajaxReturn(array("status" => -2, "result" => "会员类别信息错误"));
        }
        $property_ids = $member_class['property_ids'];
        $property_ids_arr = explode(",", $property_ids);
        $ext = array();
        if (!empty($property_ids_arr)) {
            $cond_property['property_id'] = array("IN", $property_ids_arr);
            $cond_property['status'] = MemberPropertyModel::STATUS_ACTIVE;
            $ext = M("member_property")->where($cond_property)->select();
        }
        $this->ajaxReturn(array("status" => 1, "result" => "成功", 'ext' => $ext));
    }
}
